<div class="table-responsive">
    <table class="table table-bordered" id="specTable">
        <thead>
            <tr>
                <th scope="col">图片</th>
                <th scope="col">名称</th>
                <th scope="col">原价</th>
                <th scope="col">库存</th>
                <th scope="col">优惠价格</th>
                <th scope="col">限购数量</th>
                <!-- <th scope="col">随手买价格</th> -->
                <th scope="col" class="text-center" style="width:20%">
                    <button type="button" class="btn btn-success" v-on:click="onEditSpec('')">
                        <span class="glyphicon glyphicon-plus"></span> 新增
                    </button>
                </th>
            </tr>
        </thead>
        <tbody id="specListBody">
            <tr v-for="(item,index) in specList" v-bind:key="index" class="spec-item">
                <th scope="row">
                    <img v-bind:src="item.ps_avatar" v-if="item.ps_avatar_img_id" />
                </th>
                <th scope="row">@{{ item.ps_name }}</th>
                <th scope="row">@{{ item.ps_price_underlined }}</th>
                <th scope="row">@{{ item.ps_usable_stock }}</th>
                <th scope="row">@{{ item.ps_price || '无' }}</th>
                <th scope="row">@{{ item.ps_buy_limit || '无' }}</th>
                <!-- <th scope="row">@{{ item.buy_will_price || '无' }}</th> -->
                <th scope="row" class="text-center">
                    <button type="button" class="btn btn-group-sm" v-on:click="onEditSpec(item)">编辑</button>
                    <button type="button" class="btn btn-danger btn-group-sm" style="margin-left:20px"
                        v-on:click="onDelSpec(item, index)">删除</button>
                </th>
            </tr>
            <!-- 更多行 -->
        </tbody>
    </table>
</div>
<input type="hidden" name="specs" value="{{ $specListStr }}">
<input type="hidden" name="productNumber" value="{{ $item->serial_number ?? null }}">
<div class="modal fade" id="spec_add" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"
                    style="font-size: 36px;">&times;</button>
                <h4 class="modal-title" id="spec-item-modal-title"></h4>
            </div>
            <div class="modal-body" id="specItemModel">
                <div class="form-group">
                    <label class="col-sm-2 control-label">规格图片：</label>
                    <div class="col-sm-10">
                        <div class="spec-item-img">
                            <div v-if="ItemForm.img">
                                <img v-bind:src="ItemForm.imgUrl" />
                                <span class="glyphicon glyphicon-remove-sign" v-on:click="onRemoveImg"></span>
                            </div>
                            <div v-else>
                                <input type="file" id="file-spec-item" style="display:none;" accept="image/*"
                                    v-on:change="fileUpload" />
                                <label for="file-spec-item" class="file-button">
                                    <span class="glyphicon glyphicon-plus" aria-hidden="true"
                                        style="font-size:24px"></span>
                                    <span style="margin-top:10px">上传图片</span>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 asterisk control-label">规格名称：</label>
                    <div class="col-sm-10">
                        <div class="input-group col-sm-10">
                            <input maxlength="50" type="text" class="form-control" placeholder="请输入规格名称"
                                v-model="ItemForm.name">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 asterisk control-label">规格原价：</label>
                    <div class="col-sm-10">
                        <div class="input-group col-sm-10">
                            <input maxlength="10" type="number" class="form-control" placeholder="请输入规格原价"
                                v-model="ItemForm.originalPrice">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 asterisk control-label">规格库存：</label>
                    <div class="col-sm-10">
                        <div class="input-group col-sm-10">
                            <input maxlength="10" type="number" class="form-control" placeholder="请输入规格库存"
                                v-model="ItemForm.stock">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">优惠价格：</label>
                    <div class="col-sm-10">
                        <div class="input-group col-sm-10">
                            <input maxlength="10" type="number" class="form-control" placeholder="请输入优惠价格"
                                v-model="ItemForm.price">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">限购数量：</label>
                    <div class="col-sm-10">
                        <div class="input-group col-sm-10">
                            <input maxlength="10" type="number" class="form-control" placeholder="请输入限购数量"
                                v-model="ItemForm.limitNum">
                        </div>
                    </div>
                </div>
                <!-- <div class="form-group">
                    <label class="col-sm-2 control-label">设置佣金：</label>
                    <div class="col-sm-10 flex">
                        <div class="input-group col-sm-3">
                            <label class="radio-inline">
                                <input type="radio" name="commissionType" value="1"
                                    :checked="ItemForm.commissionType == '1'"
                                    v-on:click="onChangeCommissionType(1)">固定金额
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="commissionType" value="2"
                                    :checked="ItemForm.commissionType == '2'"
                                    v-on:click="onChangeCommissionType(2)">比例佣金
                            </label>
                        </div>

                        <div class="input-group col-sm-7">
                            <input maxlength="10" type="number" class="form-control"
                                :placeholder="`请输入${ItemForm.commissionType == 1 ? '佣金金额' : ItemForm.commissionType == 2 ? '佣金比例' : ''}`"
                                v-model="ItemForm.commissionValue">
                            <span v-if="ItemForm.commissionType == 2" class="input-group-addon">%</span>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">随手买价格：</label>
                    <div class="col-sm-10">
                        <div class="input-group col-sm-10">
                            <input maxlength="10" type="number" class="form-control" placeholder="请输入"
                                v-model="ItemForm.buyWillPrice">
                        </div>
                    </div>
                </div> -->

                <div class="form-group text-center">
                    <button type="button" class="btn" data-dismiss="modal" aria-hidden="true"
                        style="margin-right: 30px">取消</button>
                    <button type="button" class="btn btn-primary spinner-border" v-on:click="specItemSubmit"
                        :disabled="submitDisabled">提交</button>
                </div>
            </div>
        </div>
    </div>
</div>
<input type="hidden" name="spec_item_info" value="" />

<script>
    $('.table-responsive').parent().parent().parent().removeClass('col-sm-10').addClass('col-sm-11').prev().removeClass(
        'col-sm-2').addClass('col-sm-1');
    const productId = '{{ $item->product_id ?? 0 }}';
    const newAuth = '{{ $newAuth }}';
    const productNumber = $("input[name='productNumber']").val() || null;
    const productRandomId = `${Date.now()}${Math.floor(1000000 + Math.random() * (9999999 - 1000000))}`;

    var specVm = new Vue({
        el: '#specTable',
        data: {
            specList: []
        },
        methods: {
            onSpecChange() {
                let specIds = specVm.specList.map(v => v.ps_id)
                let specNumbers = specVm.specList.map(v => v.serial_number)
                $("input[name='ps_id_json']").val(specIds.join(','))
                $("input[name='spec_json']").val(specNumbers.join(','))
            },
            // 编辑规格
            onEditSpec(row) {
                $('#spec_add').modal('show');
                $("input[name='spec_item_info']").val(JSON.stringify(row))
            },
            // 删除规格
            onDelSpec(row, index) {
                $.confirm({
                    title: '温馨提示',
                    content: '确认要删除该规格吗？',
                    buttons: {
                        '取消': function() {},
                        '确认': function() {
                            specVm.specList.splice(index, 1)
                            specVm.onSpecChange()
                        }
                    }
                });
            }
        },
        mounted() {
            setTimeout(() => {
                specSortableInit()

                if (productId > 0) {
                    // 初始化获取规格列表
                    let productSpecStr = $("input[name='specs']").val() || '[]'
                    let productSpecList = JSON.parse(productSpecStr)

                    productSpecList.map(v => {
                        specVm.specList.push({
                            ps_id: v.ps_id,
                            serial_number: v.serial_number,
                            ps_avatar: getImgUrlFunc(v.ps_avatar),
                            ps_avatar_img_id: v.ps_avatar_img_id || '',
                            ps_name: v.ps_name,
                            ps_price: v.ps_price,
                            ps_price_underlined: v.ps_price_underlined,
                            ps_usable_stock: v.ps_usable_stock,
                            ps_buy_limit: v.ps_buy_limit,
                            commission: v.commission,
                            commission_ratio: v.commission_ratio,
                            buy_will_price: v.buy_will_price
                        })
                    })
                    specVm.onSpecChange();
                }
            }, 500);
        }
    })

    // 拖动排序
    function specSortableInit() {
        let el = document.getElementById('specListBody');

        let specsort = new Sortable.create(el, {
            animation: 150,
            ghostClass: 'sortable-ghost', // 添加拖动时的样式
            draggable: ".spec-item",
            filter: '.not-draggable',
            ignoreFrom: '.not-draggable',
            onEnd: function({
                oldIndex,
                newIndex
            }) {
                // 使用Vue的数组操作方法进行排序
                let currentList = [...specVm.specList]
                const movedItem = currentList.splice(oldIndex, 1)[0]; // 移除旧位置的元素
                currentList.splice(newIndex, 0, movedItem); // 插入到新位置
                specVm.specList = []
                setTimeout(() => {
                    specVm.specList = [...currentList]
                    // 如果imgIdPush是一个需要在排序后调用的方法，确保它能正确工作
                    specVm.onSpecChange();
                });
            }
        });
    }

    var specItemVm = new Vue({
        el: '#specItemModel',
        data: {
            ItemForm: {
                ps_id: '',
                serial_number: '',
                img: '',
                imgUrl: '',
                name: '',
                price: '',
                originalPrice: '',
                stock: '',
                limitNum: '',
                commissionType: 1,
                commissionValue: '',
                buyWillPrice: ''
            },
            submitDisabled: false,
            btnTimer: 1500
        },
        methods: {
            onChangeCommissionType(type) {
                this.ItemForm.commissionType = type
            },
            // 图片上传
            async fileUpload(e) {
                let itemCompressedFile = await compressImage(e.target.files[0])
                let formData = new FormData();
                formData.append('file', itemCompressedFile);
                formData.append('type', 3);
                ajaxFileFunc('/v1/api/upload/image', formData, {
                    'newAuth': newAuth
                }, res => {
                    specItemVm.ItemForm.img = res.id;
                    specItemVm.ItemForm.imgUrl = getImgUrlFunc(res.serialNumber);
                })
            },
            onRemoveImg() {
                specItemVm.ItemForm.img = ''
                specItemVm.ItemForm.imgUrl = ''
            },
            specItemSubmit() {
                specItemVm.submitDisabled = true
                setTimeout(() => {
                    specItemVm.submitDisabled = false
                }, specItemVm.btnTimer);

                if (!specItemVm.ItemForm.name) {
                    $.alert('请输入规格名称');
                } else if (!specItemVm.ItemForm.originalPrice) {
                    $.alert('请输入规格原价');
                } else if (!specItemVm.ItemForm.stock) {
                    $.alert('请输入规格库存');
                } else if (parseFloat(parseFloat(specItemVm.ItemForm.price) > 0 && specItemVm.ItemForm.price) >
                    parseFloat(specItemVm.ItemForm.originalPrice)) {
                    $.alert('优惠价格不能大于规格原价');
                } else if (!specItemVm.ItemForm?.serial_number && specVm.specList.find(v => v.ps_name ==
                        specItemVm.ItemForm.name)) {
                    $.alert(`规格名称重复，该产品下已存在规格-${specItemVm.ItemForm.name}`);
                } else {
                    let params = {
                        psName: specItemVm.ItemForm.name,
                        psPriceUnderlined: parseFloat(specItemVm.ItemForm.originalPrice).toFixed(2),
                        psUsableStock: specItemVm.ItemForm.stock,
                        randProductId: productRandomId,
                    }
                    if (specItemVm.ItemForm.img) params.imgId = specItemVm.ItemForm.img
                    if (specItemVm.ItemForm.price && parseFloat(specItemVm.ItemForm.price) > 0) params.psPrice =
                        parseFloat(specItemVm.ItemForm.price).toFixed(2)
                    if (specItemVm.ItemForm.limitNum) params.psBuyLimit = specItemVm.ItemForm.limitNum
                    if (this.ItemForm.commissionType == 1 && !!this.ItemForm.commissionValue) params
                        .commission = parseFloat(this.ItemForm.commissionValue).toFixed(2)
                    if (this.ItemForm.commissionType == 2 && !!this.ItemForm.commissionValue) params
                        .commission_ratio = this.ItemForm.commissionValue
                    if (specItemVm.ItemForm.buyWillPrice && parseFloat(specItemVm.ItemForm.buyWillPrice) > 0) params.buyWillPrice =
                        parseFloat(specItemVm.ItemForm.buyWillPrice).toFixed(2)

                    if (specItemVm.ItemForm.serial_number) {
                        // 编辑
                        params.serialNumber = specItemVm.ItemForm.serial_number
                        ajaxPostFunc('/v1/api/shopProductSpec/edit', params, {
                            'newAuth': newAuth
                        }, res => {
                            let editSpecIndex = specVm.specList.findIndex(v => v.serial_number ==
                                specItemVm.ItemForm.serial_number)

                            Vue.set(specVm.specList, editSpecIndex, {
                                ps_id: specItemVm.ItemForm.ps_id,
                                serial_number: specItemVm.ItemForm.serial_number,
                                ps_avatar: specItemVm.ItemForm.imgUrl,
                                ps_avatar_img_id: specItemVm.ItemForm.img,
                                ps_name: specItemVm.ItemForm.name,
                                ps_price: specItemVm.ItemForm.price,
                                ps_price_underlined: specItemVm.ItemForm.originalPrice,
                                ps_usable_stock: specItemVm.ItemForm.stock,
                                ps_buy_limit: specItemVm.ItemForm.limitNum,
                                [this.ItemForm.commissionType == 1 ?
                                    'commission' :
                                    'commission_ratio'
                                ]: this.ItemForm.commissionValue
                            })
                            specVm.onSpecChange()
                            $('#spec_add').modal('hide');
                        })
                    } else {
                        // 新增
                        params.productNumber = productNumber
                        ajaxPostFunc('/v1/api/shopProductSpec/add', params, {
                            'newAuth': newAuth
                        }, res => {
                            specVm.specList.push({
                                ps_id: res.id,
                                serial_number: res.serialNumber,
                                ps_avatar: specItemVm.ItemForm.imgUrl,
                                ps_avatar_img_id: specItemVm.ItemForm.img,
                                ps_name: specItemVm.ItemForm.name,
                                ps_price: specItemVm.ItemForm.price,
                                ps_price_underlined: specItemVm.ItemForm.originalPrice,
                                ps_usable_stock: specItemVm.ItemForm.stock,
                                ps_buy_limit: specItemVm.ItemForm.limitNum,
                                [this.ItemForm.commissionType == 1 ?
                                    'commission' :
                                    'commission_ratio'
                                ]: this.ItemForm.commissionValue
                            })
                            specVm.onSpecChange()
                            $('#spec_add').modal('hide');
                        })
                    }
                }
            },
            // 编辑时填充数据
            getEditRowData(data) {
                if (!data) {
                    $('#spec-item-modal-title').text('新增规格')
                    specItemVm.ItemForm = {
                        img: '',
                        imgUrl: '',
                        name: '',
                        price: '',
                        originalPrice: '',
                        stock: '',
                        limitNum: '',
                        commissionType: 1,
                        commissionValue: '',
                        buyWillPrice: ''
                    }
                } else {
                    $('#spec-item-modal-title').text('编辑规格')
                    specItemVm.ItemForm = {
                        ps_id: data.ps_id,
                        serial_number: data.serial_number,
                        img: data.ps_avatar_img_id,
                        imgUrl: data.ps_avatar,
                        name: data.ps_name,
                        price: data.ps_price || '',
                        originalPrice: data.ps_price_underlined,
                        stock: data.ps_usable_stock,
                        limitNum: data.ps_buy_limit || '',
                        commissionType: data.commission_ratio ? 2 : data.commission ? 1 : '',
                        commissionValue: data.commission_ratio ? data.commission_ratio : data.commission ?
                            data.commission : '',
                        buyWillPrice: data.buy_will_price
                    }
                }
            }
        }
    })

    $(function() {
        // 监听模态框打开完成事件
        $('#spec_add').on('shown.bs.modal', function(e) {
            let postSpecItemInfo = JSON.parse($("input[name='spec_item_info']").val())

            setTimeout(() => {
                specItemVm.getEditRowData(postSpecItemInfo)
            });
        });
    })
</script>

<style scoped>
    .flex {
        display: flex;
    }

    .spec-item {
        cursor: pointer;
    }

    .spec-item img {
        display: block;
        width: 40px;
        height: 40px;
    }

    .spec-item-img {
        border: 1px solid #ccc;
        width: 100px;
        height: 100px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
    }

    .spec-item-img div {
        width: 100%;
        height: 100%;
        position: relative;
    }

    .spec-item-img img {
        display: block;
        width: 100%;
        height: 100%;
    }

    .spec-item-img .glyphicon-remove-sign {
        position: absolute;
        top: -5px;
        right: -5px;
        font-size: 20px;
        color: #999;
    }
</style>
